<!--
 * @Author: ZhaoZhiqi
 * @Date: 2022-08-09 10:41:01
 * @LastEditors: ZhaoZhiqi
 * @LastEditTime: 2022-10-24 16:57:55
 * @Description: 富文本编辑器
 * @FilePath: \tuanfeng-admin-front\src\components\Editor.vue
-->
<script setup>
import axios from "axios";
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { toRefs } from "vue";
import { ElNotification } from "element-plus";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css

const props = defineProps({
    content: {
        type: String,
        required: false,
    },
});
const { content } = toRefs(props);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref("");

// 内容初始化
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = content.value;
    }, 0);
});

const toolbarConfig = {};
const editorConfig = {
    placeholder: "请输入内容...",
    MENU_CONF: {},
};

// 自定义上传图片
editorConfig.MENU_CONF["uploadImage"] = {
    customUpload: (resultFiles, insertImgFn) => {
        const param = new FormData(); // 创建form对象
        param.append("file", resultFiles);
        const config = {
            headers: {
                "Content-Type": "multipart/form-data",
                Authorization: localStorage.getItem("tf_admin_token"),
            },
        };
        axios
            .post(
                `${import.meta.env.VITE_APP_HTTPURL}/file/upload`,
                param,
                config
            )
            .then((res) => {
                if (res.status === 200 && res.data.code === 200) {
                    insertImgFn(res.data.data.url);
                    return true;
                } else {
                    ElNotification({
                        title: "上传图片错误",
                        message: res.desc,
                        type: "error",
                    });
                }
            });
    },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};

defineExpose({ valueHtml });
</script>
<template>
    <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" />
        <Editor style="height: 500px; overflow-y: hidden;" v-model="valueHtml" :defaultConfig="editorConfig" @onCreated="handleCreated" />
    </div>
</template>
<style scoped lang="less">
</style>
